<template>
  <!-- 生产单元管理 -->
  <div class="prodUnitManager">
    <basic-container>
      <!-- 表格内容 -->
      <avue-crud :option="option"
                 :table-loading="loading"
                 :data="data"
                 :page.sync="page"
                 :permission="permissionList"
                 :before-open="beforeOpen"
                 v-model="form"
                 ref="crud"
                 @row-update="rowUpdate"
                 @row-save="rowSave"
                 @row-del="rowDel"
                 @search-change="searchChange"
                 @search-reset="searchReset"
                 @selection-change="selectionChange"
                 @current-change="currentChange"
                 @size-change="sizeChange"
                 @refresh-change="refreshChange"
                 @on-load="onLoad">
        <template slot="menuLeft">
          <el-button type="danger" size="small" icon="el-icon-delete" plain v-if="permission.prod_unit_delete" @click="handleDelete">删 除</el-button>
          <el-button type="success" size="small" icon="el-icon-upload2" plain v-if="permission.prod_unit_import" @click="handleImport">导入</el-button>
          <el-button type="warning" size="small" icon="el-icon-download" plain v-if="permission.prod_unit_export" @click="handleExport">导出</el-button>
        </template>

        <!--巡检点-->
        <template slot="ckxjjl">
          <el-form label-width="0px">
            <td style="border: 0px">
              <el-button type="primary" size="small" @click="handleCamera">查看巡检记录</el-button>
            </td>
          </el-form>
        </template>

      </avue-crud>

      <el-dialog title="生产单元区域数据导入" append-to-body :visible.sync="excelBox" width="555px">
        <avue-form :option="excelOption" v-model="excelForm" :upload-after="uploadAfter">
          <template slot="excelTemplate">
            <el-button type="primary" @click="handleTemplate">
              点击下载<i class="el-icon-download el-icon--right"></i>
            </el-button>
          </template>
        </avue-form>
      </el-dialog>

      <!-- 巡检点弹窗 -->
      <el-dialog title="选择 摄像头" :visible.sync="dialogCamera" append-to-body @close='closeDialogCamera' width="1200px" class="prodUnitXjd">
        <avue-crud :option="cameraOption"
                   :table-loading="cameraLoading"
                   :data="cameraData"
                   :page.sync="cameraPage"
                   ref="cameraCrud"
                   @search-change="cameraSearchChange"
                   @search-reset="cameraSearchReset"
                   @selection-change="cameraSelectionChange"
                   @current-change="cameraCurrentChange"
                   @size-change="cameraSizeChange">
        </avue-crud>
        <span slot="footer" class="dialog-footer">
          <el-button @click="closeDialogCamera">取 消</el-button>
          <el-button type="primary" @click="chooseCamera()">确 定</el-button>
        </span>
      </el-dialog>

    </basic-container>
  </div>
</template>

<script>
  import {getList, remove, update, add, getProdUnit, getFzrLinkInfo} from "@/api/mmhi/prod_unit";
  import {getCameraBinding} from "@/api/mmhi/major_supe_hazard_chem";
  import {getDeptList} from "@/api/mmhi/major_dangerous_sources";
  import {getToken} from "@/util/auth";
  import {mapGetters} from "vuex";

  export default {
    data() {
      return {
        form: {},
        query: {},
        excelBox: false,
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        excelForm: {},
        excelOption: {
          submitBtn: false,
          emptyBtn: false,
          column: [
            {
              label: '模板上传',
              prop: 'excelFile',
              type: 'upload',
              drag: true,
              loadText: '模板上传中，请稍等',
              showFileList: false,
              span: 24,
              propsHttp: {
                res: 'data'
              },
              tip: '请上传 .xls,.xlsx 标准格式文件',
              action: "/api/prodUnitManage/bladeProdUnit/import-prodUnit"
            },
            {
              label: '模板下载',
              prop: 'excelTemplate',
              formslot: true,
              span: 24,
            }
          ]
        },
        option: {
          height: 'auto',
          refreshBtn: true,
          columnBtn: true,
          calcHeight: 30,
          dialogWidth: 950,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          viewBtn: true,
          selection: true,
          dialogClickModal: false,
          column: [
            {
              label: "区域名称",
              prop: "qymc",
              align: "center",
              maxlength:25,
              search: true,
              rules: [{
                required: true,
                message: "请输入区域名称",
                trigger: "click"
              }]
            },
            {
              label: "所属部门",
              prop: "ssbm",
              align: "center",
              type:"tree",
              dicData: [],
              props: {
                label: "title"
              },
              checkStrictly: true,
              rules: [{
                required: true,
                message: "请选择所属部门",
                trigger: "click"
              }]
            },
            {
              label: "区域位号",
              prop: "qywh",
              align: "center",
              maxlength:25,
              rules: [{
                required: true,
                message: "请输入区域位号",
                trigger: "blur"
              }],
            },
            {
              label: "区域等级",
              prop: "qydj",
              align: "center",
              maxlength:25,
              rules: [{
                required: true,
                message: "请输入区域等级",
                trigger: "blur"
              }],
            },
            {
              label: "负责人",
              type: "select",
              align: "center",
              dicUrl: "/api/prodUnitManage/bladeProdUnit/getFzrList",
              props: {
                value: "realName"
              },
              prop: "fzr",
              rules: [{
                required: true,
                message: "请选择负责人",
                trigger: "blur"
              }]
            },
            {
              label: "负责人部门",
              prop: "fzrbm",
              align: "center",
              disabled: true
            },
            {
              label: "负责人工号",
              prop: "fzrgh",
              align: "center",
              disabled: true
            },
            {
              label: "负责人联系电话",
              width:120,
              prop: "fzrdh",
              align: "center",
              disabled: true
            },
            {
              label: "备注",
              prop: "bz",
              align: "center",
              type: "textarea",
              maxlength:25,
              span: 24,
              minRows: 6,
              hide: true
            },
            {
              label: "操作",
              width: "120px",
              prop: "ckxjjl",
              slot: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false,
              hide: false,
              align: "center"
            }
          ]
        },
        data: [],

        dialogCamera: false,
        cameraQuery: {},
        cameraLoading: true,
        cameraPage: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        cameraSelectionList: [],
        cameraOption: {
          calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          menu: false,
          addBtn: false,
          viewBtn: true,
          selection: true,
          dialogClickModal: false,
          refreshBtn: false,
          columnBtn: false,
          column: [
            {
              label: "摄像头名称",
              prop: "sxtmc",
              align: "center",
              search: true
            },
            {
              label: "摄像头ID",
              prop: "sxtid",
              align: "center"
            },
            {
              label: "安装位置",
              prop: "azwz",
              align: "center"
            },
            {
              label: "所属区域",
              prop: "ssqy",
              align: "center"
            }
          ]
        },
        cameraData: [],
        selectCamera: {}
      };
    },
    watch: {
      'form.fzr':{// form是表单或者表格绑定的数据集，v-model='form'
        handler(val){
          if(val!='' && val!=undefined && val!=null){
            getFzrLinkInfo(val).then(res=>{// 可以请求后端的方法
              this.form.fzrgh= res.data.data[0].code;
              this.form.fzrbm = res.data.data[0].deptName;
              this.form.fzrdh = res.data.data[0].phone;
            });
          }
        },
        immediate: true
      }
    },
    computed: {
      ...mapGetters(["permission"]),
      // 表格按钮权限
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.prod_unit_add, false),
          viewBtn: this.vaildData(this.permission.prod_unit_view, false),
          delBtn: this.vaildData(this.permission.prod_unit_delete, false),
          editBtn: this.vaildData(this.permission.prod_unit_edit, false)
        };
      },
      // 勾选项id
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    mounted() {
      this.initData();
    },
    methods: {
      // 初始化数据
      initData() {
        const tenantId = JSON.parse( localStorage.getItem("saber-tenantId") ).content;
        getDeptList(tenantId).then(res => {
          const column = this.findObject(this.option.column, "ssbm");
          column.dicData = res.data.data;
        }).then(() => {

        });
      },

      // 新增
      rowSave(row, done, loading) {
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message.success("操作成功!");
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      // 编辑
      rowUpdate(row, index, done) {
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message.success("操作成功!");
          done();
        });
      },
      // 删除一条
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          return remove(row.id);
        }).then(() => {
          this.onLoad(this.page);
          this.$message.success("操作成功!");
        });
      },

      // 删除多条
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          return remove(this.ids);
        }).then(() => {
          this.onLoad(this.page);
          this.$message.success("操作成功!");
          this.$refs.crud.toggleSelection();
        });
      },

      // 打开弹窗前
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getProdUnit(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },

      // 清空搜索条件
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },

      // 搜索条件改变事件
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },

      // 勾选
      selectionChange(list) {
        this.selectionList = list;
      },

      // 清空勾选
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },

      // 换页数
      currentChange(currentPage){
        this.page.currentPage = currentPage;
        this.onLoad(this.page);
      },

      // 换每页显示数量
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
        this.onLoad(this.page);
      },

      // 刷新
      refreshChange() {
        this.onLoad(this.page, this.query);
      },

      // 获取表格数据
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      },

      handleImport() {
        this.excelBox = true;
      },
      uploadAfter(res, done, loading, column) {
        window.console.log(column);
        this.excelBox = false;
        this.refreshChange();
        done();
      },
      handleTemplate() {
        window.open(`/api/prodUnitManage/bladeProdUnit/export-template?${this.website.tokenHeader}=${getToken()}`);
      },
      handleExport() {
        this.$confirm("是否导出生产区域信息数据?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          window.open(`/api/prodUnitManage/bladeProdUnit/export-prodUnit?${this.website.tokenHeader}=${getToken()}`);
        });
      },
      // 删除某一个reak标签
      closeReakTag(index) {
        this.reakTags.splice(index, 1);
        if(this.reakTags.length === 0) {
          this.reakTagsErr = true;
        }
      },

      // 打开绑定摄像头弹窗
      handleCamera() {
        this.dialogCamera = true;
        this.cameraOnLoad(this.cameraPage);
      },

      // 关闭绑定摄像头弹窗
      closeDialogCamera() {
        this.cameraPage.currentPage = 1;
        this.dialogCamera = false;
        this.cameraSelectionClear();
      },

      // 摄像头获取表格数据
      cameraOnLoad(page, params = {}) {
        this.cameraLoading = true;
        getCameraBinding(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.cameraPage.total = data.total;
          this.cameraData = data.records;
          this.cameraLoading = false;
          if(this.selectCamera !== undefined && JSON.stringify(this.selectCamera) !== "{}") {
            this.$nextTick(() => {
              this.cameraData.forEach(row => {
                if(this.selectCamera[row.id] !== undefined) {
                  this.$refs.cameraCrud.toggleRowSelection(row, true);
                }
              })
            })
          }
        });
      },

      // 绑定摄像头清空勾选
      cameraSelectionClear() {
        this.cameraSelectionList = [];
        this.$refs.cameraCrud.toggleSelection();
      },

      // 摄像头搜索条件改变事件
      cameraSearchChange(params, done) {
        this.cameraQuery = params;
        this.cameraPage.currentPage = 1;
        this.cameraOnLoad(this.cameraPage, params);
        done();
      },

      // 摄像头清空搜索条件
      cameraSearchReset() {
        this.cameraQuery = {};
        this.cameraOnLoad(this.cameraPage);
      },

      // 摄像头勾选
      cameraSelectionChange(list) {
        this.cameraSelectionList = list;
      },

      // 摄像头换页数
      cameraCurrentChange(currentPage){
        const pageSelectIds = [];
        const pageAllIds = [];
        this.cameraSelectionList.forEach(item => {
          this.selectCamera[item.id] = item;
          pageSelectIds.push(item.id);
        });
        this.cameraData.forEach(item => {
          pageAllIds.push(item.id);
        });
        for(let id in this.selectCamera) {
          if(pageSelectIds.indexOf(id) < 0 && pageAllIds.indexOf(id) >= 0) {
            delete this.selectCamera[id];
          }
        }
        this.cameraPage.currentPage = currentPage;
        this.cameraOnLoad(this.cameraPage);
      },

      // 摄像头换每页显示数量
      cameraSizeChange(pageSize){
        this.cameraPage.pageSize = pageSize;
        this.cameraOnLoad(this.cameraPage);
      },

      // 选择摄像头
      chooseCamera() {
        const pageSelectIds = [];
        const pageAllIds = [];
        this.cameraSelectionList.forEach(item => {
          this.selectCamera[item.id] = item;
          pageSelectIds.push(item.id);
        });
        this.cameraData.forEach(item => {
          pageAllIds.push(item.id);
        });
        for(let id in this.selectCamera) {
          if(pageSelectIds.indexOf(id) < 0 && pageAllIds.indexOf(id) >= 0) {
            delete this.selectCamera[id];
          }
        }

        this.closeDialogCamera();
      }

    }
  };
</script>

<style lang="scss">
  .prodUnitManager {
    .el-form-item__label {
      width: 86px !important;
    }

    .avue-form__row {
      .el-form-item__content {
        margin-left: 86px !important;
      }
    }
  }

  .prodUnitXjd {
    .el-form-item__label {
      width: 100px !important;
    }
    .avue-form__row {
      .el-form-item__content {
        margin-left: 100px !important;
      }
    }
  }

</style>

<style lang="scss" scpoed>
  .avue-crud__dialog {
    .el-dialog__body {
      .el-form-item__label {
        width: 95px !important;
      }

      .avue-form__row {
        .el-form-item__content {
          margin-left: 95px !important;
        }
      }
    }
  }

  .el-dialog__wrapper {
    .el-dialog__body {
      padding: 10px 20px 20px 20px;

      .el-form-item__label {
        width: 72px;
      }

      .avue-form__row {
        .el-form-item__content {
          margin-left: 72px;
        }
      }

      .avue-crud__menu {
        display: none;
      }
    }
  }
</style>
